<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title></title>
		
	</head>
	<body>
		
	</body>
	<script type="text/javascript">
	//初始化考虑重力加速度的各个方向的值
		var x = 0;
		var y = 0;
		var z = 0;
		var lastX = 0;//摇晃事件，上一次的值
		var lastY = 0;
		var lastZ = 0;
		var maxSpeed = 3000;//摇晃激烈程度临界值
		var num = 0;//摇晃的次数
		var lastTime = 0;//上一次摇晃的时间
		if(window.DeviceMotionEvent){
			window.addEventListener("devicemotion",shakeFn,false)
		}else{
			alert("不支持");
		}
		function shakeFn(event){
			//获取设备包含重力加速度的加速度值
			var ag =  event.accelerationIncludingGravity;
			//获取当前的毫秒数
			var curTime =new Date().getTime();
			//如果本次摇晃跟上次摇晃事件事件差值大于100毫秒，才算做下一次摇晃
			if((curTime - lastTime) > 100){
				var diffTime = curTime - lastTime;//两次摇晃时间差值
				//保存上一次摇晃的时间，
				lastTime = curTime;
				//各个方向的加速度值
				x = ag.x;
				y = ag.y;
				z = ag.z;
				var speed =Math.abs((x + y + z - lastX - lastY - lastZ)/diffTime*10000);//计算摇晃的激烈程度
				if(speed > maxSpeed){
					alert("牛逼");
					num++;
					document.body.innerHTML = "您晃了" + num + "次，速度是" + speed;
				}
				//保存上一次摇晃的速度。
				lastX = x;
				lastY = y;
				lastZ = z;
			}
		}
	</script>
</html>
